<?php

use C\L\Task;
use C\M\GroupBuyingOrder;
use C\M\GroupBuyingGoods;

class AutoGenerateGroupBuyingOrderTask extends Task
{
    public function runAction()
    {
        $count = $this->checkConfig();

        for ($i = 0; $i < $count; $i++) {
            $goods = $this->getRandomGoods();
            if (!$goods) {
                $this->logs(['msg' => '未找到符合条件的团购商品']);
            }

            $user = $this->generateUser();

            $this->di['s_group_buying_order']->confirmFakeOrder($goods, $user);
        }
    }

    private function checkConfig()
    {
        $config = $this->s_config->get('auto_generate_order');
        if (!$config) {
            $this->logs(['msg' => '未检测到相关配置']);
            return 0;
        }

        if ($config['status'] != 'enabled') {
            $this->logs(['msg' => '未开启自动发起团购功能']);
            return 0;
        }

        $count = GroupBuyingOrder::count([
        'conditions' => 'state = :state:',
        'bind' => ['state' => 'processing'],
        ]);

        if ($count >= $config['max']) {
            $this->logs(['msg' => '已达到团购订单上限']);
            return 0;
        }

        return $config['status'] === 'enabled'
        ? min($config['velocity'], $config['max'] - $count)
        : 0;
    }

    private function getRandomGoods()
    {
        return GroupBuyingGoods::findFirst([
        'conditions' => 'status = :status: AND stock > 0',
        'bind'       => ['status' => 'on_sale'],
        'order'      => 'rand()',
        ]);
    }

    private function generateUser()
    {
        return [
        'id'     => 0,
        'mobile' => $this->generateMobile(),
        ];
    }

    private function generateMobile()
    {
        $prefixes = [
        '130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
        '150', '151', '152', '153', '155', '156', '157', '158', '159',
        '166',
        '173', '175', '176', '177', '178',
        '180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
        '191', '198', '199',
        ];
        $sequence = $prefixes[array_rand($prefixes)] .
        $this->generateRandomSequence(8, 0, 9);

        return $sequence;
    }

    private function generateRandomSequence($requiredLength, $lowestDigit = 0, $highestDigit = 8)
    {
        $sequence = '';
        for ($i = 0; $i < $requiredLength; ++$i) {
            $sequence .= mt_rand($lowestDigit, $highestDigit);
        }
        return $sequence;
    }
}
